import React, { Component } from 'react';
import {
  StyleSheet, Text, View, Alert, Image, ScrollView, Animated
} from "react-native";
import MethodUtil from '../../../../utils/MethodUtil';
import { GLOBAL } from '../../../../config/global';
import { CREDIT_TYPES } from '../../../../config/definition';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { SpaceBetween } from '../../create/_components/SpaceBetween.js';
import { MorePage } from '../../create/_components/MorePage.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { ApproveButton } from './_component/approveButton';
import { RefuseModal } from './modals/refuse';
import { ProductSection } from './_component/ProductSection';
import { FeeSection } from './_component/FeeSection';
import { DeliveryPlanSection } from './_component/DeliveryPlanSection';
import { StateSection } from './_component/StateSection';
import OrderApproveService from '../_common/service';
import { TASK_KEY } from '../_common/service';
import ToastUtil from '../../../../utils/toast';
import { CURRENCY } from '../../../../utils/helper';
const scale = GLOBAL.SCALE;

const sendData = {};

export class BackToBackSalePage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      headerTitle: '闭口销售成交报告审批',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: style.head.headerStyle,
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  requesting;
  constructor(props) {
    super(props);
    this.orderId = props.navigation.state.params.paramsData.orderId;
    this.orderType = props.navigation.state.params.paramsData.orderType;
    this.companyId = props.navigation.state.params.paramsData.companyId;
    this.businessKey = props.navigation.state.params.paramsData.businessKey;
    this.taskId = props.navigation.state.params.paramsData.taskId;
    this.formKey = props.navigation.state.params.paramsData.formKey;
    this.status = props.navigation.state.params.status;
    this.companyName = props.navigation.state.params.paramsData.companyName;
    this.auditResultName = props.navigation.state.params.paramsData.auditResultName;
    this.taskType = props.navigation.state.params.paramsData.taskType;

    this.animateData = {
      basic: {
        start: {   // 初始值
          value: 120,
          text: '展开更多'
        },
        end: {  // 介素值
          value: 320,
          text: '收起'
        }
      },
    }

    this.state = {
      data: {},
      basicAnim: new Animated.Value(this.animateData.basic.start.value),
      saleAnim: new Animated.Value(this.animateData.basic.start.value),
      basicOnoff: true,
      saleOnoff: true,
      loaded: false,
      profitList: []
    }
  }

  componentWillMount () {
    this._getDetailData(this.orderId);//详情数据
    this._getProfitData(this.orderId);//盈利数据
  }

  //获取盈利数据
  async	_getProfitData (orderId) {
    let responseData = await OrderApproveService.getProfitData({ orderId });
    if (responseData) {
      this.setState({
        profitList: responseData
      })
    }
  }

  //初始化详情数据
  async _getDetailData (orderId) {
    this.setState({
      loaded: true
    });

    let responseData = await OrderApproveService.getApproveDetail({ approveType: this.approveType }, {
      orderId,
      queryType: 'ORDER_ALL_INFO',
    });

    this.setState({
      loaded: false
    });

    if (responseData) {
      this.setState({
        data: responseData
      })
    }
  }

  // animatedFn
  _animatedFn = (num, animateObj) => {
    Animated.timing(
      animateObj,
      {
        duration: 300,
        toValue: num
      }
    ).start();
  }

  // 基本信息  更多设置
  _onPressFn = (data, objOnoff, name, animateObj) => {
    if (objOnoff) {
      this._animatedFn(data.end.value, animateObj);
    } else {
      this._animatedFn(data.start.value, animateObj);
    }
    if (name == 'basicOnoff') {
      this.setState({
        basicOnoff: !objOnoff
      })
    }
    if (name == 'saleOnoff') {
      this.setState({
        saleOnoff: !objOnoff
      })
    }

  }

  approveAgree () {
    sendData.status = 'PASS';
    Alert.alert('提示', '确定要同意此成交报告吗？', [
      {
        text: '再想想',
      }, {
        text: '确定',
        onPress: () => {
          this._fetchApproval('1');
        }
      }
    ]);
  }

  approveRefuse () {
    this.setState({
      refuseModalVisible: true
    })
  }

  async _fetchApproval (numStr) {
    if (this.requesting) return;
    this.setState({ refuseModalVisible: false, loaded: true });
    this.requesting = true;
    const responseData = await OrderApproveService.goApprove({ approveType: this.approveType }, {
      businessKey: this.businessKey,
      taskId: this.taskId,
      formKey: this.formKey,
      auditResult: numStr,
      remark: this.remark, // 填写
    });

    this.setState({
      loaded: false
    });
    if (responseData) {
      ToastUtil.showSuccess((numStr == '0') ? '驳回成功' : '审批成功').then(() => {
        this._goBack();
      });
    } else {
      this.requesting = false;
    }
  }

  // 返回上一个页面
  _goBack = () => {
    setTimeout(() => {
      this.requesting = false;
    }, 1000)
    this.props.navigation.goBack();
  }

  render () {
    let { data, basicOnoff, basicAnim, saleOnoff, saleAnim } = this.state;
    let { bizStaffName, priceType, companyName, orderId, orderItemList, orderFeeList, otherCost, currency, orderDeliveryPlanList, orderType, oppoOrderInfo } = data;
    oppoOrderInfo = oppoOrderInfo ? oppoOrderInfo : ''
    let saleInfo = (orderType === 'P' ? oppoOrderInfo : data);//销售订单基本信息
    let purchaseInfo = (orderType === 'P' ? data : oppoOrderInfo);//采购订单基本信息
    let basicCss = basicOnoff ? { height: basicAnim } : null;
    let saleCss = saleOnoff ? { height: saleAnim } : null;
    return (
      <View style={styles.container}>
        <View style={styles.emptyBg}>
        </View>
        <ScrollView style={{ paddingTop: 10 * scale }}>
          <View style={styles.itemBox}>
            <Animated.View style={[basicCss, styles.animateBg]}>
              <Text style={styles.itemTitle}>基本信息(采购成交)</Text>
              <SpaceBetween fontLeft={{ title: '订单编号' }} fontRight={{ title: purchaseInfo.orderId }} />
              <SpaceBetween fontLeft={{ title: '供应商' }} fontRight={{ title: purchaseInfo.companyName }} />
              <SpaceBetween fontLeft={{ title: '申请人' }} fontRight={{ title: bizStaffName }} />
              <SpaceBetween fontLeft={{ title: '付款类型' }} fontRight={{ title: purchaseInfo.payTypeName }} />
              {CREDIT_TYPES[purchaseInfo.orderType] && CREDIT_TYPES[purchaseInfo.orderType][purchaseInfo.payType] ? <Text style={styles.credit}>授信可用金额 {CURRENCY.getUnit(currency).label + MethodUtil.toThousands(purchaseInfo.creditInfo && purchaseInfo.creditInfo.limitAmount || 0) + CURRENCY.getUnit(currency).text}  有效期至{purchaseInfo.creditInfo && purchaseInfo.creditInfo.creditEndDate}</Text> : null}
              {purchaseInfo.prepayRate ? <SpaceBetween fontLeft={{ title: '定金比例' }} fontRight={{ title: purchaseInfo.prepayRate + '%' }} /> : null}
              {purchaseInfo.payExpireDays ? <SpaceBetween fontLeft={{ title: OrderApproveService.setPayTypeName(purchaseInfo.payType) }} fontRight={{ title: purchaseInfo.payExpireDays + '天内付款' }} /> : null}
              {purchaseInfo.deliveryExpireDays && '4' === purchaseInfo.payType ? <SpaceBetween fontLeft={{ title: '款到' }} fontRight={{ title: purchaseInfo.deliveryExpireDays + '天内交货' }} /> : null}
              <SpaceBetween fontLeft={{ title: '付款方式' }} fontRight={{ title: purchaseInfo.payStyleName }} />
              {/*<SpaceBetween fontLeft={{ title: '有效合同起始日期' }} fontRight={{ title: purchaseInfo.exeBeginDate + '至' + purchaseInfo.exeEndDate }} />*/}
              <SpaceBetween fontLeft={{ title: '币种' }} fontRight={{ title: purchaseInfo.currencyName || '人民币' }} />
              {purchaseInfo.baseDateSettleName ? <SpaceBetween fontLeft={{ title: '结算基准日期' }} fontRight={{ title: purchaseInfo.baseDateSettleName }} /> : null}
              <SpaceBetween fontLeft={{ title: '交货方式' }} fontRight={{ title: saleInfo.orderType == 'P' ? saleInfo.purchaseDeliveryTypeName : saleInfo.saleDeliveryTypeName }} />
              {purchaseInfo.lostRenderName && purchaseInfo.deliveryType && 'U' != purchaseInfo.deliveryType ? <SpaceBetween fontLeft={{ title: '运损承担方' }} fontRight={{ title: purchaseInfo.lostRenderName }} /> : null}
              {purchaseInfo.lostRate ? <SpaceBetween fontLeft={{ title: '途损率' }} fontRight={{ title: '千分之' + MethodUtil.countObj.multiply(purchaseInfo.lostRate, 1000) }} /> : null}
              {purchaseInfo.freeDays ? <SpaceBetween fontLeft={{ title: '免仓期' }} fontRight={{ title: purchaseInfo.freeDays + '天' }} /> : null}
              {purchaseInfo.companyContactorName ? <SpaceBetween fontLeft={{ title: '对方企业业务员' }} fontRight={{ title: purchaseInfo.companyContactorName }} /> : null}
              {purchaseInfo.settleDisputesName ? <SpaceBetween fontLeft={{ title: '争议处理方式' }} fontRight={{ title: purchaseInfo.settleDisputesName }} /> : null}
            </Animated.View>
            <MorePage text={basicOnoff ? this.animateData.basic.start.text : this.animateData.basic.end.text} onPressFn={() => { this._onPressFn(this.animateData.basic, basicOnoff, 'basicOnoff', basicAnim) }} />
          </View>

          <View style={[styles.itemBox, styles.borders]}>
            <Animated.View style={[saleCss, styles.animateBg]}>
              <Text style={styles.itemTitle}>基本信息(销售成交)</Text>
              <SpaceBetween fontLeft={{ title: '订单编号' }} fontRight={{ title: saleInfo.orderId }} />
              <SpaceBetween fontLeft={{ title: '客户' }} fontRight={{ title: saleInfo.companyName }} />
              <SpaceBetween fontLeft={{ title: '申请人' }} fontRight={{ title: bizStaffName }} />
              <SpaceBetween fontLeft={{ title: '收款类型' }} fontRight={{ title: saleInfo.payTypeName }} />
              {CREDIT_TYPES[saleInfo.orderType] && CREDIT_TYPES[saleInfo.orderType][saleInfo.payType] ? <Text style={styles.credit}>授信可用金额 {CURRENCY.getUnit(currency).label + MethodUtil.toThousands(saleInfo.creditInfo && saleInfo.creditInfo.limitAmount || 0) + CURRENCY.getUnit(currency).text}  有效期至{saleInfo.creditInfo && saleInfo.creditInfo.creditEndDate}</Text> : null}
              {saleInfo.prepayRate ? <SpaceBetween fontLeft={{ title: '定金比例' }} fontRight={{ title: saleInfo.prepayRate + '%' }} /> : null}
              {saleInfo.payExpireDays ? <SpaceBetween fontLeft={{ title: OrderApproveService.setPayTypeName(saleInfo.payType) }} fontRight={{ title: saleInfo.payExpireDays + '天内收款' }} /> : null}
              {saleInfo.deliveryExpireDays && '4' === saleInfo.payType ? <SpaceBetween fontLeft={{ title: '款到' }} fontRight={{ title: saleInfo.deliveryExpireDays + '天内交货' }} /> : null}
              <SpaceBetween fontLeft={{ title: '收款方式' }} fontRight={{ title: saleInfo.payStyleName }} />
              {/*<SpaceBetween fontLeft={{ title: '有效合同起始日期' }} fontRight={{ title: saleInfo.exeBeginDate + '至' + saleInfo.exeEndDate }} />*/}
              <SpaceBetween fontLeft={{ title: '币种' }} fontRight={{ title: saleInfo.currencyName || '人民币' }} />
              {saleInfo.baseDateSettleName ? <SpaceBetween fontLeft={{ title: '结算基准日期' }} fontRight={{ title: saleInfo.baseDateSettleName }} /> : null}
              <SpaceBetween fontLeft={{ title: '交货方式' }} fontRight={{ title: saleInfo.orderType == 'P' ? saleInfo.purchaseDeliveryTypeName : saleInfo.saleDeliveryTypeName }} />
              {saleInfo.lostRenderName && saleInfo.deliveryType && 'U' != saleInfo.deliveryType ? <SpaceBetween fontLeft={{ title: '运损承担方' }} fontRight={{ title: saleInfo.lostRenderName }} /> : null}
              {saleInfo.lostRate ? <SpaceBetween fontLeft={{ title: '途损率' }} fontRight={{ title: '千分之' + MethodUtil.countObj.multiply(saleInfo.lostRate, 1000) }} /> : null}
              {saleInfo.freeDays ? <SpaceBetween fontLeft={{ title: '免仓期' }} fontRight={{ title: saleInfo.freeDays + '天' }} /> : null}
              {saleInfo.companyContactorName ? <SpaceBetween fontLeft={{ title: '对方企业业务员' }} fontRight={{ title: saleInfo.companyContactorName }} /> : null}
              {saleInfo.settleDisputesName ? <SpaceBetween fontLeft={{ title: '争议处理方式' }} fontRight={{ title: saleInfo.settleDisputesName }} /> : null}
            </Animated.View>
            <MorePage text={saleOnoff ? this.animateData.basic.start.text : this.animateData.basic.end.text} onPressFn={() => { this._onPressFn(this.animateData.basic, saleOnoff, 'saleOnoff', saleAnim) }} />
          </View>
          <ProductSection data={data} taskType={OrderApproveService.TASK_KEY[this.taskType]} />
          <FeeSection data={orderFeeList} currency={currency} otherCost={otherCost} />
          <DeliveryPlanSection data={orderDeliveryPlanList} title={'交货计划(采购成交)'} />
          <DeliveryPlanSection data={orderDeliveryPlanList} title={'交货计划(销售成交)'} />
        </ScrollView>
        <StateSection data={{ orderId, companyName: companyName ? companyName : this.companyName, auditResultName: this.auditResultName }} />
        {
          this.status && this.status === 'LOT' ? (
            <View style={{ backgroundColor: '#fff' }}>
              <ApproveButton agreePress={() => { this.approveAgree(); }} refusePress={() => { this.approveRefuse(); }} />
            </View>
          ) : null
        }
        <RefuseModal
          visible={this.state.refuseModalVisible}
          btnPress={(remark) => {
            this.remark = remark;
            this._fetchApproval('0');
          }}
          bgPress={() => {
            this.setState({
              refuseModalVisible: false,
            });
          }} />
        {
          this.state.loaded ?
            <View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
              <PageStatusIndex status='loading' />
            </View>
            : null
        }
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.white,
  },
  emptyBg: {
    height: 39 * scale,
    backgroundColor: style.color.themeColor,
    marginBottom: 13 * scale,
  },
  budget: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  itemBox: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    paddingBottom: 13 * scale,
    backgroundColor: '#fff'
  },
  itemTitle: {
    fontSize: 14 * scale,
    color: style.color.themeColor,
    height: 20 * scale,
    lineHeight: 20 * scale,
    marginTop: 12 * scale,
    marginBottom: 12 * scale
  },
  borders: {
    borderTopWidth: 12 * scale,
    borderStyle: 'solid',
    borderTopColor: style.color.dullGrey,
  },
  animateBg: {
    backgroundColor: style.color.white
  },
  credit: {
    fontSize: 13 * scale,
    color: '#f86765',
    padding: 4 * scale
  }
})